package com.ly.mpayment.rest.system;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import com.ly.mpayment.core.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.entity.User;
import com.ly.mpayment.persist.service.uprechargerecord.IUpRechargeRecordService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;

import net.sf.json.JSONObject;

@Component
@Path("system/uprecharge/")
public class UpRechargeRest extends AbsRest {
	@Autowired
	IUserService userService;

	@Autowired
	IUpShopInfoService upService;

	@Autowired
	IUpRechargeRecordService upRechargeService;
	Logger logger = Logger.getLogger(UpRechargeRest.class);
	/**
	 * 上游充值
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("upRecharge")
	@POST
	public String downRecharge(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "upshopuuid","upshopbalance","remark","recharge");
		if(result == null){
			JSONObject json = JsonUtils.converToJson(data);
			//检查操作用户是否是管理员操作，只有管理员才能操作
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject userInfo = JsonUtils.converToJson(jwt.getSubject());
						if (userInfo != null) {
							User adminUser = userService.findByUserid(userInfo.getString(Config.tokenSignAttr));
							if(adminUser != null && UserUtil.checkRole(adminUser)){
								UpShopInfo shop = upService.findById(json.getString("upshopuuid"));
								if(shop != null){
									int paytype = json.getInt("recharge") == 1 ? 1 : 2;
									if(paytype == Config.RECHARGE[0]){
//										shop.setUpshopbalance(shop.getUpshopbalance().add(BigUtil.getBigDecimal(json.getString("upshopbalance"))));
										json.put("remark", json.getString("remark").equals("") ? Config.recharge[0] : json.getString("remark"));
									}else{
//										shop.setUpshopbalance(shop.getUpshopbalance().subtract(BigUtil.getBigDecimal(json.getString("upshopbalance"))));
										json.put("remark",  json.getString("remark").equals("") ? Config.recharge[1] : json.getString("remark"));
									}
									if(this.upService.updateShopAmount(shop,adminUser,BigUtil.getBigDecimal(json.getString("upshopbalance")),json.getString("remark"),paytype)){
										return ResultMessage.getSucceed(null);
									}
									return ResultMessage.getFailt("");
								}
								return ResultMessage.getFailt(ResultMessage.shopexistError);
							}
							return ResultMessage.getFailt(ResultMessage.notAuthority);
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	@Path("findRechargeRecord")
	@POST
	public String findRechargeRecord(String data, @Context HttpServletRequest request) {
		String result = this.validationParameterGetRole(request, userService);
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!StringUtils.isBlank(json.getString("starttime"))) {
				parameters.put(":starttime", json.getString("starttime"));
			}
			if (!StringUtils.isBlank(json.getString("endtime"))) {
				parameters.put(":endtime", json.getString("endtime"));
			}
			if (!StringUtils.isBlank(json.getString("useruuid"))) {
				parameters.put(":useruuid", json.getString("useruuid"));
			}
			return ResultMessage.getSucceed(
					JsonUtils.excludes(this.upRechargeService.findPageUprechargerecord(parameters, json.getInt("start"),
							json.getInt("pageSize")), new String[] { "platFormAccount","errorCodesForUseruuid","createtime","useruuid",
									"password","","wechatid","lastlogintime" ,"token","usertype" ,"userstatus","phonenum"}));
		}
		return result;
	}


	@Path("exportUpRechargeRecord")
	@POST
	public String exportUpRechargeRecord(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService, "start", "pageSize", "starttime","useruuid","",
				"endtime");
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!StringUtils.isBlank(json.getString("starttime"))) {
				parameters.put(":starttime", json.getString("starttime"));
			}
			if (!StringUtils.isBlank(json.getString("endtime"))) {
				parameters.put(":endtime", json.getString("endtime"));
			}
			if (!StringUtils.isBlank(json.getString("useruuid"))) {
				parameters.put(":useruuid", json.getString("useruuid"));
			}
			JSONObject obj = JsonUtils.getJSONOBJCT();
			String exportResult = ExportExcelUtil.exportUpRechargeRecord(this.upRechargeService.findPageUprechargerecord(parameters,0,1000000));
			logger.info("exportResult:"+exportResult);
			if(exportResult != null){
				obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
				return ResultMessage.getSucceed(obj.toString());
			}else{
				return ResultMessage.getFailt("");
			}
		}
		return result;
	}

	@Path("upRecordCount")
	@POST
	public String upRecordCount(String data, @Context HttpServletRequest request) {
		String result = this.validationParameterGetRole(request, userService );
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!StringUtils.isBlank(json.getString("starttime"))) {
				parameters.put(":starttime", json.getString("starttime"));
			}
			if (!StringUtils.isBlank(json.getString("endtime"))) {
				parameters.put(":endtime", json.getString("endtime"));
			}
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject userInfo = JsonUtils.converToJson(jwt.getSubject());
						if (userInfo != null) {
							User adminUser = userService.findByUserid(userInfo.getString(Config.tokenSignAttr));
							if (adminUser != null && UserUtil.checkRoleDown(adminUser)) {
								parameters.put(":useruuid", adminUser.getUseruuid());
							}
							if(!StringUtils.isBlank(json.getString("useruuid"))){
								parameters.put(":useruuid", json.getString("useruuid"));
							}
							return ResultMessage.getSucceed(
									JsonUtils.excludes(this.upRechargeService.findUpRecordCount(parameters, json.getInt("start"),
											json.getInt("pageSize")), new String[] { "platFormAccount","errorCodesForUseruuid","createtime","useruuid",
											"password","","wechatid","lastlogintime" ,"token","usertype" ,"userstatus","phonenum" }));
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}

}
